package com.steve.xfood.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 操作Cookie工具类
 * @author steve
 * @date 2020/5/27 10:27
 */
public class CookieUtil {

    /**
     * 设置cookie
     */
    public static void set(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name,value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 获取cookie
     * @return
     */
    public static Cookie get(HttpServletRequest request,
                             String name) {
        Map<String, Cookie> cookieMap = readCookieMap(request);
        if (cookieMap.containsKey(name)) {
            //如果cookie列表中包含name，则直接返回
            return cookieMap.get(name);
        } else {
            return null;
        }
    }

    /**
     * 把cookie封装到Map集合
     * @param request
     * @return
     */
    private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<>();
        //获取cookie列表
        Cookie[] cookies = request.getCookies();
        if(cookies !=null) {
            //如果cookie列表不为空
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
}
